package com.suyafei.mq;

import com.rabbitmq.client.Channel;
import com.suyafei.model.OrderMessage;
import com.suyafei.service.ProductOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @program: suyafei-1024-shop
 * @description
 * @author: luffy
 * @create: 2021-03-25 22:52
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.order_close_queue}")
public class ProductOrderMQListener {

    @Autowired
    private ProductOrderService productOrderService;


    /**
     * 幂等性保证
     * 并发情况下如何保证安全
     * @param orderMessage
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void closeProductOrder(OrderMessage orderMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息  closeProductOrder ：{}", orderMessage);

        long msgTag = message.getMessageProperties().getDeliveryTag();

        try {
            boolean flag = productOrderService.closeProductOrder(orderMessage);
            if (flag) {
                channel.basicAck(msgTag, false);
            }else {
                channel.basicReject(msgTag, true);
            }
        } catch (Exception e) {
            log.error("定时关单失败{}",e);
            channel.basicReject(msgTag, true);
        }
    }
}
